﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using MVCPets.Models;
using MVCPets.Helpers;

namespace MVCPets.Controllers
{
  [HandleError]
  public class AccountController : BaseController
  {
    public IFormsAuthenticationService FormsService { get; set; }
    public IMembershipService MembershipService { get; set; }

    protected override void Initialize(RequestContext requestContext)
    {
      if (MembershipService == null) { MembershipService = new AccountMembershipService(); }
      if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
      
      base.Initialize(requestContext);
    }

    public ActionResult LogOn()
    {
      return View();
    }

    [HttpPost]
    public ActionResult LogOn(LogOnModel model, string returnUrl)
    {
      if (ModelState.IsValid)
      {
        if (MembershipService.ValidateUser(model.EmailAddress, model.Password))
        {
          SessionHelper.UserRole = UserModel.GetUserRole(model.EmailAddress);

          FormsService.SignIn(model.EmailAddress, model.RememberMe);
          
          if (!String.IsNullOrEmpty(returnUrl)) return Redirect(returnUrl);
          else return RedirectToAction("Index", "Home");
        }
        else
        {
          ModelState.AddModelError("", "The user name or password provided is incorrect.");
        }
      }

      // If we got this far, something failed, redisplay form
      return View(model);
    }

    
    public ActionResult LogOff()
    {
      FormsService.SignOut();

      return RedirectToAction("Index", "Home");
    }

    public ActionResult Register()
    {
      ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
      return View();
    }

    [HttpPost]
    public ActionResult Register(RegisterModel model)
    {
      if (ModelState.IsValid)
      {
        // Attempt to register the user
        var createStatus = MembershipService.CreateUser(model.Email, model.Password);

        if (createStatus == MembershipCreateStatus.Success)
        {
          FormsService.SignIn(model.Email, false /* createPersistentCookie */);
          return RedirectToAction("Index", "Home");
        }
        else
        {
          ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
        }
      }

      // If we got this far, something failed, redisplay form
      ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
      
      return View(model);
    }

    [Authorize, HttpGet]
    public ActionResult ChangePassword()
    {
      ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
      return View();
    }

    [Authorize, HttpPost]
    public ActionResult ChangePassword(ChangePasswordModel model)
    {
      if (ModelState.IsValid)
      {
        if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
        {
          return RedirectToAction("ChangePasswordSuccess");
        }
        else
        {
          ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
        }
      }

      // If we got this far, something failed, redisplay form
      ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
      
      return View(model);
    }

    public ActionResult ChangePasswordSuccess()
    {
      return View();
    }
  }
}
